package org.theSeed.base.utils;

import cn.hutool.core.util.ObjectUtil;
import lombok.SneakyThrows;
import org.theSeed.base.exp.ServiceExp;

import java.io.*;

/**
 * 深拷贝工具
 */
public class DeepCopyUtil {
    /**
     * 深拷贝
     * @return
     * @param <T>
     */
    @SneakyThrows
    public static <T> T deepCopy(T obj){
        if (ObjectUtil.isNull(obj)){
            return null;
        }
        if (!(obj instanceof Serializable)){
            throw new ServiceExp(SeedStringUtil.concatStr("深拷贝对象",obj.getClass().toString(),"需要继承Serializable"));
        }

        T res;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)){
            oos.writeObject(obj);
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            res = (T) ois.readObject();
            bis.close();
            ois.close();
        }
        return res;
    }
}
